import websocket
import time
import threading
import json
import requests
from loguru import logger


def on_open(wsapp):
    logger.info("on_open")

    def send_message():
        for i in range(5):
            wsapp.send(f"Hello {i}")
            time.sleep(1)

    threading.Thread(target=send_message).start()


def on_data(wsapp, frame_data, frame_opcode, frame_fin):
    logger.info("on_data", frame_data, frame_opcode, frame_fin, sep=", ")
    # 客户手机号
    phone = '18664342053'
    result_data = json.loads(frame_data)
    if result_data['data']['invoke_command'] == "GetSMSCount_Multi":
        logger.info("获取短信条数的接口返回...")
        if result_data['dynamicdata']['usedcount'] > 0:
            number = result_data['dynamicdata']['usedcount']
            logger.info("一共读取到{}条数据...".format(number))
            for i in range(number):
                wsapp.send('''{"command":"ReadSms_Multi","arguments":{"content":"''' + str(i) + '''","devicename":"EV78220230216741"}}''')
                time.sleep(0.3)
        else:
            logger.info("没有短信数据...")
            # 发送心跳
            post_heart(phone)
    elif result_data['data']['invoke_command'] == "ReadSms_Multi":
        logger.info("获取短信内容的接口返回...")
        content = result_data['dynamicdata']['content']
        index = result_data['dynamicdata']['index']
        logger.info("正在推送短信内容...")
        post_data(wsapp, phone, content, index)

def on_message(wsapp, data):
    # logger.info("on_message", data, sep=", ")
    pass

def post_data(wsapp, phone, content, index):
    url = "http://1.95.166.150:8997/api/v1/sms/save"
    data = {
        "phone": phone,
        "text": content
    }
    logger.info("参数：{}".format(data))
    try:
        response = requests.post(url, json=data)
        logger.info(response.text)
        wsapp.send('''{"command":"DeleteSMS_Multi","arguments":{"content":"'''+str(index)+'''","devicename":"EV78220230216741"}}''')
    except Exception as e:
        logger.info(e)

def post_heart(phone):
    url = "http://1.95.166.150:8997/api/v1/sms/heart"
    data = {
        "phoneOrIp": phone,
        "type": "慕迪短信"
    }
    try:
        # logger.info("发送心跳")
        requests.post(url, json=data)
    except Exception as e:
        logger.info(e)


def on_cont_message(wsapp, frame_data, frame_fin):
    logger.info("on_cont_message", frame_data, frame_fin, sep=", ")


def on_ping(wsapp, frame_data):
    logger.info("on_ping", frame_data, sep=", ")
    # 接收到 PING 数据帧后, 需要立即给服务端回复 PONG 数据帧
    wsapp.send("", websocket.ABNF.OPCODE_PONG)


def on_pong(wsapp, frame_data):
    logger.info("on_pong", frame_data, sep=", ")
    wsapp.send('''{"command":"GetSMSCount_Multi","arguments":{"devicename":"EV78220230216741"}}''')


def on_error(wsapp, e):
    logger.info("on_error", e, sep=", ")


def on_close(wsapp, close_status_code, close_reason):
    logger.info("on_close", close_status_code, close_reason, sep=", ")


wsapp = websocket.WebSocketApp("ws://127.0.0.1:8555/api",
                               on_open=on_open,
                               on_data=on_data,
                               on_message=on_message,
                               on_cont_message=on_cont_message,
                               on_ping=on_ping,
                               on_pong=on_pong,
                               on_error=on_error,
                               on_close=on_close)

wsapp.run_forever(ping_interval=5, ping_timeout=2)
